/*
*	封装文件上传组件 demo
*/

var page_static_fn = {};
var page_container = null;  	//部分情况下可能由于IE版本问题会取不到值，注意下异步即可
page_container = $("#container").get(0) || document.getElementById("container");
var upload;
$(function(){
	try{
		upload = new xyd_upload();//xyd_plupload-template.js
	}catch(e){
		throw new Error("object xyd_upload undefined");
		return;
	}
	
	upload.settings = {
		url : 'http://localhost:8080/plupload/upload',	//服务器端的上传页面地址
		type : 'all',									//文件类型,如果为空则不允许上传
		size : '500mb',									//文件大小
		swf : xyd.sys.plupload.js.swf,					//swf文件，当需要使用swf方式进行上传时需要配置该参数
		xap : xyd.sys.plupload.js.xap,					//silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
		btn_openFileId : "openFilesTest",				//触发文件选择对话框的按钮，为那个元素id
		node_box : page_container						//节点容器，用于创建结构
		
	};

	upload.init(upload.settings);
	
	var plup = upload.getPlupUploadObject();
	
	/*************************************************************************
	*	事件控制区
	*************************************************************************/
	
	//绑定按钮打开文件
	$("#docOpen").bind("click",function(){
		$("#openFilesTest").click();
	});
	
	//选择文件
	upload.bindEvent("FilesAdded",function(up,files){
		page_static_fn.FileChanged(files);
		page_static_fn.createFilesUI($(upload.settings.node_box),files);
	});
	
	//开始上传
	$("#start_upload").bind("click",function(){
		if(plup.files.length<1){
			layer.msg("没有可上传的文件...",{time:3000});
			return false;
		}
		page_static_fn.FileUploadStart();
		upload.setFileAllState(upload.getFiles());
		upload.start();
	});
	
	//单个文件开始上传
	upload.bindEvent("UploadFile",function(up,file){
		//upload.getPlupUploadObject().setOption({multipart_params:{uuid:file.id}});
		page_static_fn.FileStateAnimate(file);
	});
	
	//单个文件上传前动作
	upload.bindEvent("BeforeUpload",function(up,file){
		var plup = upload.getPlupUploadObject();
		var f = plup.getFile(file.id);
		plup.setOption({multipart_params:{uuid:f.id+f.name}});
		page_static_fn.FileStateAnimate(file);
	});
	

	//单文件进度条
	upload.bindEvent("uploadProgress",function(up,file){
		page_static_fn.uploadProgress(up,file);
	});
	
	//文件队列变化时
	upload.bindEvent("QueueChanged",function(up){
		page_static_fn.FileChanged(up.files);
	});
	
	//单个文件上传完成
	upload.bindEvent("FileUploaded",function(up,file,responseObject){
		if(file.status===5){		
			try{
				var strName;
				strName = responseObject.response;
				strName = strName.replace("<script>", "");
				strName = strName.replace("</script>", "");
				file.newFileName = strName;
			}catch(e){}
			page_static_fn.FileMoveNode(file);
		}
		page_static_fn.FileStateAnimate(file);
	});
	
	//全部文件上传完成
	upload.bindEvent("UploadComplete",function(up,files){
		page_static_fn.UploadComplete(up);
	});
	
	//发生错误
	upload.bindEvent("Error",function(up,err){
		page_static_fn.FileStateAnimate(err.file);
		var json = upload.formatErr(err);
		/*
		var html = "<div class=\"alert alert-warning\" style=\"margin:0;padding:5px;\">"
					+ "<button data-dismiss=\"alert\" class=\"close\" type=\"button\">"
					+ "<i class=\"ace-icon fa fa-times\"></i>"
					+ "</button>"
					+ "<pre style=\"border:0;background:none;margin:0;padding:0;\">"
					+ json.err+"，&#9;"+json.file+"</pre>"
					+ "</div>";
					
		$("#console").append(html);
		$(html).css({"padding":"5px","font-size":"12px","line-height":"20px","border-bottom":"0px solid #ccc"});
		*/
		layer.msg(json.err,{time:2000});
	});
	
	
	
	/*************************************************************************
	*	节点操作区
	*************************************************************************/
	
	//根据Files创建节点
	page_static_fn.createFilesUI = function(elNode,files){
		
		plupload.each(files, function(file) {
			var fileFix = String(upload.getFileTypeFx(file.name)).toLowerCase();
			
			var newIcon;
			if(fileFix!='jpg' && fileFix!=='gif' && fileFix!=='png'){
				newIcon = $("<i></i>");
				newIcon.addClass("ace-icon "+upload.options.uploadTypeIcon.none);
				$(newIcon).css({
					"width":"100px",
					"height":"100px",
					"color":"#999",
					"font-size":"4em",
					"padding-top":"23px"
				});
				newIcon = newIcon.prop("outerHTML");
			}else{
				newIcon = "<img id=\"images-file-"+file.id+"\"/>";
			}
			
			var newHTML = "<div class=\"imagesList\" id=\"file-" + file.id + "\" title=\""+file.name+"\">"
							+ "<div class=\"btn-file-del\"><i class=\"ace-icon fa fa-trash-o fa-1x icon-only\" onclick=\"page_static_fn.FileRemove('"+file.id+"')\"></i></div>"
							+ "<div class=\"imagesBox\">"
							+ newIcon
							+ "</div>"
							+ "<div class=\"title\">"+file.name+"</div>"
						+ "</div>"
			
			if(fileFix=='jpg' || fileFix=='gif' || fileFix=='png'){
				upload.previewImage(file, function (imgsrc) {
					$('#images-file-' + file.id).attr("src",imgsrc);	
				})
			}
			
			var el = $(newHTML).insertBefore(elNode);

			el.hover(function(){
				$(this).find(".btn-file-del").slideDown(200);
			},function(){
				$(this).find(".btn-file-del").hide();
				
			});
			
			page_static_fn.FileStateAnimate(file);

		});
		
		$("#FileList").sortable();
		$("#FileList").disableSelection();  
	}
	

	//文件队列变化时
	page_static_fn.FileChanged = function(files){
		$("#file_select").html("当前 "+files.length+" 个文件，大小合计 "+upload.formatSize(upload.getFileSizeCount(files)));
	}
	

	//开始上传前
	page_static_fn.FileUploadStart = function(){	
		var el = $("#uploadProgress_box");
	}
	
	
	//单文件进度条
	page_static_fn.uploadProgress = function(up,file){
		var el = $("#uploadProgress_box");
		if(!el){return;}
		el.find(".uploadFix").css({"width":file.percent+"%"});
		el.find(".uploadFileState").html(
			"正在上传 "+file.name+"，已上传 "+file.percent+"%"
			//+"% ， 速度："+upload.formatSize(up.total.bytesPerSec,3)+" / S "
		);
		
	}
	
	
	//移动节点
	page_static_fn.FileMoveNode = function(file){
		var el = $("#file-"+file.id);
		//$("#FileSucceed").append(el);
	}
	
	
	//单文件实时状态
	page_static_fn.FileStateAnimate = function(file){
		var el = $("#file-"+file.id);
		var box,dom;
		if(el.find(".ico-file-state-box").length<1){
			dom = $("<div></div>");
			box = $("<div></div>");
			
			el.append(box);
			el.append(dom);
		}else{
			box = el.find(".ico-file-state-box");
			dom = el.find(".ico-file-state-bean");
			box.attr("class","");
			dom.attr("class","");
		}
		box.addClass("ico-file-state-box");
		dom.addClass("ico-file-state-bean");
		
		var status = file.status;
		//status = 2;
		var icon,color;
		if(status>1 || status<6){
			icon = $("<i></i>"),color = {"color":"#ffffff"};
		}
		
		if(status===1){
			//准备就绪
		}else if(status===2){
			//正在上传
			icon.addClass("ace-icon fa fa-refresh fa-spin fa-1x fa-fw");
			icon.attr("title","正在上传...");
			color = {"color":"#1094FA"};
			box.addClass("uploadFile-state2");
			dom.addClass("ico-file-state-bean-s2");
		}else if(status===4){
			//上传失败
			box.addClass("uploadFile-state4");
			icon.addClass("ace-icon fa fa-refresh");
			icon.attr("onclick","page_static_fn.newStartFile('"+file.id+"')");
			icon.attr("title","重新上传");
		}else if(status===5){
			//上传成功
			icon.addClass("ace-icon glyphicon glyphicon-ok");
			icon.attr("title","上传成功");
			box.addClass("uploadFile-state5");
		}else{
			
		}
		
		dom.css(color).html(icon.prop("outerHTML"));
	}
	
	//上传完成
	page_static_fn.UploadComplete = function(){
		var el = $("#uploadProgress_box");
		if(!el){return;}
		el.find(".uploadFix").css({"width":"0%"});
		var files = upload.getFiles();
		var succeed = 0;
		var error = 0;
		for(var i=0;i<files.length;i++){
			if(files[i].status===5){
				succeed += 1;
			}else{
				error += 1;
			}
		}
		
		if(error>0){
			error = "<span style=\"color:#f00\">" + error + "</span>";
		}
		
		str = "共上传 "+files.length+" 个，成功 " + succeed + " 个，失败 " + error + "</span> 个";
		
		el.find(".uploadFileState").html(str);
		
	}
	
	//重新上传
	page_static_fn.newStartFile = function(id){
		var plup = upload.getPlupUploadObject();
		var f = plup.getFile(id);
		plup.setOption({multipart_params:{uuid:f.id+f.name}});
		upload.newStartFile(id);
	}
	
	//删除文件
	page_static_fn.FileRemove = function(id){
		upload.removeFile(id);
		$("#file-"+id).fadeOut("fast", function (){
			$(this).remove();
		});
	}
	
	//取出上传成功的文件
	page_static_fn.getUploadSucceed = function(){
		var filesNode = $("#FileList").find(".imagesList");
		var str = "";
		$.each(filesNode,function(){
			var $this = $(this);
			var id = $this.attr("id");
			id = id.replace("file-", "");
			var file = upload.getFile(id);
			if(file!==undefined && file.status===5){
				str += file.newFileName+",";
			}
		});
		
		if(str!==""){
			str = str.substring(0,str.length-1);
		}
		return str;
	}

	
	/*
	*	网络图片
	*/
	
	var image_from = $("#profile4");	
	var image_url = image_from.find("input[name='image_url']");
	var image_box = image_from.find("#image_box");
	var btn_url_insert = image_from.find("#FileInsert");
	var image_view = image_from.find("#imageView");
	
	/*
	image_url.on("input",function(){
		var $this = $(this).val();
		setTimeout(function(){
			image_box.find("img").attr("src",$this);
		},100);
	});
	*/
	btn_url_insert.click(function(){
		if(image_url.val()==""){
			layer.msg("请输入地址...",{time:3000});
			return;
		}
		var temp = {
			id : xyd.fn.createUUID(),
			name : image_url.val()
		};
		page_static_fn.createImageUI(image_view,[temp]);
	});
	
	
	//创建图片节点
	page_static_fn.createImageUI = function(FileNode,files){
		plupload.each(files, function(file,index) {
			var fileFix = String(upload.getFileTypeFx(file.name)).toLowerCase();
			if(fileFix=='null'){
				fileFix = "文件"+(index+1)
			}
			var newIcon;
			if(fileFix!='jpg' && fileFix!=='gif' && fileFix!=='png'){
				newIcon = $("<i></i>");
				newIcon.attr("id","images-file-"+file.id);
				newIcon.attr("src",file.name);
				newIcon.addClass("ace-icon "+upload.options.uploadTypeIcon.none);
				$(newIcon).css({
					"width":"100px",
					"height":"100px",
					"color":"#999",
					"font-size":"4em",
					"padding-top":"23px"
				});
				newIcon = newIcon.prop("outerHTML");
			}else{
				newIcon = "<img id=\"images-file-"+file.id+"\" src=\""+file.name+"\" />";
			}
			
			var newHTML = "<div class=\"imagesList\" id=\"file-" + file.id + "\" title=\""+file.name+"\">"
							+ "<div class=\"btn-file-del\"><i class=\"ace-icon fa fa-trash-o fa-1x icon-only\" onclick=\"page_static_fn.FileRemove('"+file.id+"')\"></i></div>"
							+ "<div class=\"imagesBox\">"
							+ newIcon
							+ "</div>"
							+ "<div class=\"title\">"+file.name+"</div>"
						+ "</div>"
			
			var el = $(newHTML);
			FileNode.append(el);
			el.hover(function(){
				$(this).find(".btn-file-del").slideDown(200);
			},function(){
				$(this).find(".btn-file-del").hide();
				
			});
		});
		
		FileNode.sortable();
		FileNode.disableSelection();
	}
	
	//取出网络图片
	page_static_fn.getNetFiles = function(){
		var filesNode = image_view.find(".imagesList");
		var str = "";
		$.each(filesNode,function(){
			var $this = $(this);
			var id = $this.attr("id");
			id = id.replace("file-", "images-file-");
			str += $this.find("#"+id).attr("src")+",";
		});
		if(str!==""){
			str = str.substring(0,str.length-1);
		}
		return str;
	}
	
	
	//取出地址
	page_static_fn.publicGetFiles = function(){
		var a = $("#myTab4").find("li");
		var submitClass;
		$.each(a,function(){
			var $this = $(this);
			var ref = $this.attr("class");
			if(ref=='active'){
				submitClass = $this.find("a").attr("href");
			}
		});
		if(submitClass=="#home4"){
			return page_static_fn.getUploadSucceed();
		}else if(submitClass=="#profile4"){
			return page_static_fn.getNetFiles();
		}
		return undefined;
	}
});


